/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package merlion.crm.sopm.session;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.ejb.Stateless;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.ejb.EJB;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import merlion.common.entity.JobToDo;
import merlion.common.entity.SystemUserAccount;
import merlion.common.session.stateless.JobListSessionBeanLocal;
import merlion.common.session.stateless.SystemUserSessionBeanLocal;
import merlion.common.util.Consts;
import merlion.common.util.exception.NotExistException;
import merlion.crm.sopm.entity.ItemLine;
import merlion.crm.sopm.entity.PurchaseOrder;
import merlion.crm.sopm.entity.RequestForQuotation;
import merlion.crm.sopm.entity.SalesInquiry;
import merlion.crm.sopm.entity.SalesOrder;
import merlion.crm.sopm.entity.SalesQuotation;
import merlion.mrp.atpm.entity.PendingATP;
import merlion.mrp.ppm.entity.Product;
import merlion.scm.lcm.entity.DeliveryOrder;
import merlion.scm.lcm.session.LogisticControlSessionBeanLocal;

/**
 *
 * @author Yuwei nd Hong nd ZY
 */
@Stateless
public class SOPSessionBean implements SOPSessionBeanLocal, SOPSessionBeanRemote {

    @PersistenceContext
    private EntityManager entityManager;
    @EJB
    private LogisticControlSessionBeanLocal lcSessionBean;
    @EJB
    private JobListSessionBeanLocal jobSession;
    @EJB
    private SystemUserSessionBeanLocal userSession;

    public SOPSessionBean() {
    }
    
    public Boolean checkDuplicatePoNumber(String poNum){
        Query query = entityManager.createQuery("SELECT p FROM PurchaseOrder p WHERE p.poNumber =:p1");
        query.setParameter("p1", poNum);
        List<PurchaseOrder> resultList = query.getResultList();
        if(resultList.isEmpty()){
            //poNumber not existed before
            return true;
        }else{
            return false;
        }
    }

    @Override
    public PurchaseOrder savePurchaseOrder(PurchaseOrder purchaseOrder) {
        try {
            entityManager.merge(purchaseOrder);
            entityManager.flush();

            Query query = entityManager.createQuery("SELECT p FROM PurchaseOrder p WHERE p.poNumber =:p1");
            query.setParameter("p1", purchaseOrder.getPoNumber());
            purchaseOrder = (PurchaseOrder) query.getSingleResult();

            List<DeliveryOrder> dos = (List<DeliveryOrder>) purchaseOrder.getDeliveryOrders();
            if (dos.size() == 1) {
                dos.get(0).setDeliveryOrderIdStr(lcSessionBean.generateDeliveryOrderId());
                entityManager.merge(dos.get(0));
                entityManager.flush();
            } else {
                DeliveryOrder d1 = dos.get(0);
                DeliveryOrder d2 = dos.get(1);
                d1.setDeliveryOrderIdStr(lcSessionBean.generateDeliveryOrderId());
                entityManager.merge(d1);
                entityManager.flush();

                d2.setDeliveryOrderIdStr(lcSessionBean.generateDeliveryOrderId());
                entityManager.merge(d2);
                entityManager.flush();
            }

            query = entityManager.createQuery("SELECT p FROM PurchaseOrder p WHERE p.poNumber =:p1");
            query.setParameter("p1", purchaseOrder.getPoNumber());
            return (PurchaseOrder) query.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public SalesOrder saveSalesOrder(SalesOrder salesOrder) {
        try {
            entityManager.merge(salesOrder);
            entityManager.flush();
            Query query = entityManager.createQuery("SELECT s FROM SalesOrder s WHERE s.salesOrderIdStr=:p1");
            query.setParameter("p1", salesOrder.getSalesOrderIdStr());
            return (SalesOrder) query.getSingleResult();

//        }catch(NotExistException nee){
//            System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + "cannot find salesorder by date");
//            return null;
        } catch (Exception e) {
            System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Exception caught " + e.getMessage());
            return null;
        }
    }

    @Override
    public String saveChangedSalesOrder(SalesOrder so) {
        try {
            entityManager.merge(so);
            entityManager.flush();
            Query query = entityManager.createQuery("SELECT s FROM SalesOrder s WHERE s.salesOrderIdStr=:p1");
            query.setParameter("p1", so.getSalesOrderIdStr());
            so = (SalesOrder) query.getSingleResult();
            return so.getSalesOrderStatus();
        } catch (Exception e) {
            return null;
        }
    }
//     private SalesOrder getSalesOrderByDate(Timestamp date) throws NotExistException {
//        Query query = entityManager.createQuery("SELECT so FROM SalesOrder so WHERE so.salesOrderDate =:p1");
//        query.setParameter("p1", date);
//        if (query.getResultList().isEmpty()) {
//            throw new NotExistException("Not exist such sales order by date");
//        }
//        SalesOrder so = (SalesOrder) query.getResultList().get(0);
//        return so;
//    }

    @Override
    public RequestForQuotation saveRequestForQuotation(RequestForQuotation requestForQuotation) {
        try {
            entityManager.merge(requestForQuotation);
            entityManager.flush();
            return requestForQuotation;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public SalesQuotation saveSalesQuotation(SalesQuotation sq) {
        try {
            entityManager.merge(sq);
            entityManager.flush();
            Query query = entityManager.createQuery("SELECT sq FROM SalesQuotation sq WHERE sq.quotationDate=:p1");
            query.setParameter("p1", sq.getQuotationDate());
            SalesQuotation salesQ = (SalesQuotation) query.getSingleResult();

            List<DeliveryOrder> dos = (List<DeliveryOrder>) salesQ.getDeliveryOrders();
            if (dos.size() == 1) {
                dos.get(0).setDeliveryOrderIdStr(lcSessionBean.generateDeliveryOrderId());
                entityManager.merge(dos.get(0));
                entityManager.flush();
            } else {
                DeliveryOrder d1 = dos.get(0);
                DeliveryOrder d2 = dos.get(1);
                d1.setDeliveryOrderIdStr(lcSessionBean.generateDeliveryOrderId());
                entityManager.merge(d1);
                entityManager.flush();

                d2.setDeliveryOrderIdStr(lcSessionBean.generateDeliveryOrderId());
                entityManager.merge(d2);
                entityManager.flush();
            }

            // need to check whether correct or not; edited by zy
            int size = salesQ.getDeliveryOrders().size();
            List<DeliveryOrder> deos = new ArrayList<DeliveryOrder>(salesQ.getDeliveryOrders());
            for (int i = 0; i < size; i++) {
                DeliveryOrder deo = deos.get(i);
                deo = entityManager.find(DeliveryOrder.class, deo.getId());
                if (deo.getIndicativeLeadTime() != null && deo.getIndicativeLeadTime().equals("Pending")) {
                    
                    // TODO : create job (edited by zy)
                    JobToDo jobTD = new JobToDo();
                    jobTD.setJobType(Consts.JOB_TYPE_SIMULATE_PENDING_SQ);
                    jobTD.setRelatedId(deo.getSalesQuotation().getId());
                    jobTD.setStatus(Consts.JOB_STATUS_PENDING);
                    Calendar calendar = Calendar.getInstance();
                    Date date = calendar.getTime();
                    Timestamp currentTime = new Timestamp(date.getTime());
                    jobTD.setCreatedDate(currentTime);
                    SalesQuotation sqo = jobSession.getRelatedSalesQuotation(deo.getSalesQuotation().getId());
                    jobTD.setTitle(Consts.JOB_TYPE_SIMULATE_PENDING_SQ_TITLE);
                    jobTD.setContent(Consts.JOB_TYPE_SIMULATE_PENDING_SQ_CONTENT + " " + sqo.getSqNumber());
                    ArrayList<String> rolenames = new ArrayList<String>();
                    SystemUserAccount sua = userSession.getRandomProductionMgmtLevelAccount();
                    jobSession.addNewJob(sua.getId(), jobTD);

                    // add pending atp
                    PendingATP pending = new PendingATP(Consts.PENDING_RFQ, deo.getLeadTimeTS());  //change to counts!
                    //DeliveryOrder deo = getDeliveryOrderById(order.getId());
                    pending.setDeliveryOrder(deo);
                    entityManager.merge(pending);
                    entityManager.flush();
                }
            }

            return salesQ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public SalesQuotation saveEditSalesQuotation(SalesQuotation sq) {
        try {
            entityManager.merge(sq);
            entityManager.flush();
            Query query = entityManager.createQuery("SELECT sq FROM SalesQuotation sq WHERE sq.quotationDate=:p1");
            query.setParameter("p1", sq.getQuotationDate());
            SalesQuotation salesQ = (SalesQuotation) query.getSingleResult();

            // need to check whether correct or not; edited by zy
            int size = salesQ.getDeliveryOrders().size();
            List<DeliveryOrder> deos = new ArrayList<DeliveryOrder>(salesQ.getDeliveryOrders());
            for (int i = 0; i < size; i++) {
                DeliveryOrder deo = deos.get(i);
                deo = entityManager.find(DeliveryOrder.class, deo.getId());
                if (deo.getIndicativeLeadTime() != null && deo.getIndicativeLeadTime().equals("Pending")) {
                    
                    // TODO : create job (edited by zy)
                    JobToDo jobTD = new JobToDo();
                    jobTD.setJobType(Consts.JOB_TYPE_SIMULATE_PENDING_SQ);
                    jobTD.setRelatedId(deo.getSalesQuotation().getId());
                    jobTD.setStatus(Consts.JOB_STATUS_PENDING);
                    Calendar calendar = Calendar.getInstance();
                    Date date = calendar.getTime();
                    Timestamp currentTime = new Timestamp(date.getTime());
                    jobTD.setCreatedDate(currentTime);
                    SalesQuotation sqo = jobSession.getRelatedSalesQuotation(deo.getSalesQuotation().getId());
                    jobTD.setTitle(Consts.JOB_TYPE_SIMULATE_PENDING_SQ_TITLE);
                    jobTD.setContent(Consts.JOB_TYPE_SIMULATE_PENDING_SQ_CONTENT + " " + sqo.getSqNumber());
                    jobSession.addNewJob(sqo.getCustomerExecutive().getSystemUserAccount().getId(), jobTD);

                    Query query1 = entityManager.createQuery("SELECT pending FROM PendingATP pending WHERE pending.deliveryOrder.id=:p1");
                    query1.setParameter("p1", deo.getId());
                    List<PendingATP> pending = (List<PendingATP>) query1.getResultList();
                    if(pending == null || pending.isEmpty()){
                    // add pending atp
                    PendingATP pending1 = new PendingATP(Consts.PENDING_RFQ, deo.getLeadTimeTS());  //change to counts!
                    //DeliveryOrder deo = getDeliveryOrderById(order.getId());
                    pending1.setDeliveryOrder(deo);
                    entityManager.merge(pending1);
                    entityManager.flush();
                    }
                    else {
                        PendingATP pending1 = pending.get(0);
                        pending1.setRequestedTime(deo.getLeadTimeTS());
                        entityManager.merge(pending1);
                        entityManager.flush();
                    }
                        
                }
            }

            return salesQ;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//    @Override
//    public ArrayList<Integer> getOrderDiscounts(ArrayList<Long> productIds, ArrayList<Integer> orderQtys){
//        ArrayList<Integer> discounts = new ArrayList<Integer>();
//        for(int i = 0; i < 4; i++){
//            product = entityManager.find(Product.class, productIds.get(i));
//            discounts.add(5);//use queries to get discounts
//        }
//        return discounts;
//    }

//    public void updatePurchaseOrder(PurchaseOrder purchaseOrder)throws Exception {
//        throw new UnsupportedOperationException("Not supported yet.");
//    }
//    public Boolean validatePurchaseOrder(SalesQuotation salesQuotation)throws Exception{
//        Boolean validation = true; 
//        if(purchaseOrder.getSalesQuotation().getId()!= salesQuotation.getId())
//            validation = false;
//   
//        return validation; 
//    }
    @Override
    public PurchaseOrder viewPurchaseOrder(Long id) throws Exception {
        PurchaseOrder purchaseOrder = entityManager.find(PurchaseOrder.class, id);
        if (purchaseOrder == null) {
            throw new Exception("The purchase order doesn't exist!");
        }
        return purchaseOrder;
    }

    @Override
    public void createSalesOrder(PurchaseOrder purchaseOrder) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void updateSalesOrder(SalesOrder salesOrder) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ArrayList<SalesOrder> viewHistoricalSalesOrder() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ArrayList<Product> getProducts() {
        ArrayList<Product> products = new ArrayList<Product>();
        //products.add(getProduct);
        return products;
    }

    @Override
    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @Override
    public SalesInquiry saveSalesInquiry(SalesInquiry sl) {
        try {
            entityManager.merge(sl);
            entityManager.flush();
            Query query = entityManager.createQuery("SELECT si FROM SalesInquiry si WHERE si.inquiryDate=:p1");
            query.setParameter("p1", sl.getInquiryDate());
            return (SalesInquiry) query.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public PurchaseOrder getPurchaseOrderById(String idStr) throws NotExistException {
        Query query = entityManager.createQuery("SELECT po FROM PurchaseOrder po WHERE po.poNumber =:p1");
        query.setParameter("p1", idStr);
        if (query.getResultList().isEmpty()) {
            throw new NotExistException("Not exist purchase order");
        }
        PurchaseOrder purchaseOrder = (PurchaseOrder) query.getResultList().get(0);
        return purchaseOrder;
    }

    @Override
    public SalesOrder getSalesOrderById(String idStr) throws NotExistException {
        Query query = entityManager.createQuery("SELECT so FROM SalesOrder so WHERE so.salesOrderIdStr =:p1");
        query.setParameter("p1", idStr);
        if (query.getResultList().isEmpty()) {
            throw new NotExistException("Not exist Sales Order");
        }
        SalesOrder salesOrder = (SalesOrder) query.getResultList().get(0);
        return salesOrder;
    }

    @Override
    public RequestForQuotation getRequestForQuotationById(String idStr) throws NotExistException {
        Query query = entityManager.createQuery("SELECT rfq FROM RequestForQuotation rfq WHERE rfq.rfqNumber =:p1");
        query.setParameter("p1", idStr);

        if (query.getResultList().isEmpty()) {
            throw new NotExistException("Not exist purchase order");
        }
        RequestForQuotation requestForQuotation = (RequestForQuotation) query.getResultList().get(0);
        return requestForQuotation;
    }

    @Override
    public SalesInquiry getSalesInquiryById(String idStr) throws NotExistException {
        Query query = entityManager.createQuery("SELECT si FROM SalesInquiry si WHERE si.siNumber =:p1");
        query.setParameter("p1", idStr);

        if (query.getResultList().isEmpty()) {
            throw new NotExistException("Not exist purchase order");
        }
        SalesInquiry salesInquiry = (SalesInquiry) query.getResultList().get(0);
        return salesInquiry;
    }

    @Override
    public SalesQuotation getSalesQuotationById(String idStr) throws NotExistException {
        Query query = entityManager.createQuery("SELECT sq FROM SalesQuotation sq WHERE sq.sqNumber =:p2");
        query.setParameter("p2", idStr);
        if (query.getResultList().isEmpty()) {
            throw new NotExistException("Not exist sales quotation");
        }
        SalesQuotation salesQuotation = (SalesQuotation) query.getResultList().get(0);
        return salesQuotation;
    }

    @Override
    public List<PurchaseOrder> getAllPurchaseOrders() {
        Query query = entityManager.createQuery("SELECT po FROM PurchaseOrder po");
        return query.getResultList();
    }

    @Override
    public List<SalesOrder> getAllSalesOrders() {
        Query query = entityManager.createQuery("SELECT so FROM SalesOrder so");
        return query.getResultList();
    }

    @Override
    public List<RequestForQuotation> getAllRequestForQuotation() {
        Query query = entityManager.createQuery("SELECT rfq FROM RequestForQuotation rfq");
        return query.getResultList();
    }

    @Override
    public List<SalesQuotation> getAllSalesQuotation() {
        Query query = entityManager.createQuery("SELECT sq FROM SalesQuotation sq");
        return query.getResultList();
    }

    @Override
    public List<SalesInquiry> getAllSalesInquirys() {

        Query query = entityManager.createQuery("SELECT si FROM SalesInquiry si");
        return query.getResultList();
    }

    @Override
    public List<SalesQuotation> getAllSalesQuotations() {
        Query query = entityManager.createQuery("SELECT sq FROM SalesQuotation sq");
        return query.getResultList();
    }

    @Override
    public String generateSalesInquiryId() {

        //Get date YYYYMMDD
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String frontId = sdf.format(cal.getTime());

        //Query Saleslead table, anything like 'yyMMdd'
        Query query = entityManager.createQuery("SELECT s FROM SalesInquiry s WHERE s.siNumber LIKE :p1");
        query.setParameter("p1", "%" + frontId + "%");

        //Get result size
        int size = query.getResultList().size() + 1;
        String backId = String.format("%04d", size);

        //Set new ID to 'YYYYMMDD' + 'size + 1'
        String id = "SI" + frontId + "/" + backId;
        //return id
        return id;
    }

    @Override
    public String generateSalesQuotationId() {

        //Get date YYYYMMDD
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String frontId = sdf.format(cal.getTime());

        //Query Saleslead table, anything like 'yyMMdd'
        Query query = entityManager.createQuery("SELECT s FROM SalesQuotation s WHERE s.sqNumber LIKE :p1");
        query.setParameter("p1", "%" + frontId + "%");

        //Get result size
        int size = query.getResultList().size() + 1;
        String backId = String.format("%04d", size);

        //Set new ID to 'YYYYMMDD' + 'size + 1'
        String id = "SQ" + frontId + "/" + backId;
        //return id
        return id;
    }

    @Override
    public String generateSalesOrderId() {
        //Get date YYYYMMDD

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String frontId = sdf.format(cal.getTime());

        //Query SalesOrder table, anything like 'yyMMdd'
        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s WHERE s.salesOrderIdStr LIKE :p1");
        query.setParameter("p1", "%" + frontId + "%");
        System.out.println("########################### SOP session at line 333 " + frontId);

        //Get result size
        int size = query.getResultList().size() + 1;
        System.out.println("########################### SOP session at line 337 " + size);
        String backId = String.format("%04d", size);

        //Set new ID to 'YYYYMMDD' + 'size + 1'
        String id = "SO" + frontId + "/" + backId;
        //return id
        return id;
    }

    @Override
    public HashMap getSalesFiguireLstOfLst(int numOfYears) {
        Query query = entityManager.createQuery("SELECT so FROM SalesOrder so WHERE so.salesOrderStatus=:p1");
        query.setParameter("p1", Consts.ORDER_SHIPPED);
        List<SalesOrder> sos = (List<SalesOrder>) query.getResultList();
        HashMap result = new HashMap();
        // initialization
        for (int i = 0; i < 4; i++) {
            HashMap oneYearOneBar = new HashMap();
            for (int j = Consts.BASE_YEAR; j < Consts.BASE_YEAR + numOfYears; j++) {
                ArrayList<Long> twelveMonth = new ArrayList<Long>();
                for (int k = 0; k < 13; k++) {
                    Long number = new Long(0);
                    twelveMonth.add(number);
                }
                oneYearOneBar.put(new Long(j), twelveMonth);
            }
            result.put(new Long(i), oneYearOneBar);
        }
        // populate the values
        for (SalesOrder so : sos) {
            Timestamp createdDate = so.getSalesOrderDate();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            int month = Integer.valueOf(sdf.format(createdDate));
            sdf = new SimpleDateFormat("yyyy");
            int year = Integer.valueOf(sdf.format(createdDate));

            Collection<DeliveryOrder> ols = so.getDeliveryOrders();
            for (DeliveryOrder ol : ols) {
                Collection<ItemLine> ils = ol.getItemLines();
                for (ItemLine il : ils) {
                    String productTypeStr = il.getProduct().getProductType();
                    HashMap yearsOfLines;
                    if (productTypeStr.equals(Consts.ProductType.BAR_A.getText())) {
                        yearsOfLines = (HashMap) result.get(new Long(0));
                    } else if (productTypeStr.equals(Consts.ProductType.BAR_B.getText())) {
                        yearsOfLines = (HashMap) result.get(new Long(1));
                    } else if (productTypeStr.equals(Consts.ProductType.BAR_C.getText())) {
                        yearsOfLines = (HashMap) result.get(new Long(2));
                    } else {
                        yearsOfLines = (HashMap) result.get(new Long(3));
                    }
                    ArrayList<Long> monthsOfQty = (ArrayList<Long>) yearsOfLines.get(new Long(year));
                    monthsOfQty.set(month, monthsOfQty.get(month) + il.getQtyOrderedCase());
                    monthsOfQty.set(0, monthsOfQty.get(0) + monthsOfQty.get(month));

                }
            }
        }
        return result;
    }

    @Override
    public HashMap getSalesRevenueFiguresLstOfLst(int numOfYears) {
        Query query = entityManager.createQuery("SELECT so FROM SalesOrder so WHERE so.salesOrderStatus=:p1");
        query.setParameter("p1", Consts.ORDER_SHIPPED);
        List<SalesOrder> sos = (List<SalesOrder>) query.getResultList();
        HashMap result = new HashMap();
        // initialization
        for (int i = 0; i < 4; i++) {
            HashMap oneYearOneBar = new HashMap();
            for (int j = Consts.BASE_YEAR; j < Consts.BASE_YEAR + numOfYears; j++) {
                ArrayList<Long> twelveMonth = new ArrayList<Long>();
                for (int k = 0; k < 13; k++) {
                    Long number = new Long(0);
                    twelveMonth.add(number);
                }
                oneYearOneBar.put(new Long(j), twelveMonth);
            }
            result.put(new Long(i), oneYearOneBar);
        }
        // populate the values
        for (SalesOrder so : sos) {
            Timestamp createdDate = so.getSalesOrderDate();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            int month = Integer.valueOf(sdf.format(createdDate));
            sdf = new SimpleDateFormat("yyyy");
            int year = Integer.valueOf(sdf.format(createdDate));

            Collection<DeliveryOrder> ols = so.getDeliveryOrders();
            for (DeliveryOrder ol : ols) {
                Collection<ItemLine> ils = ol.getItemLines();
                for (ItemLine il : ils) {
                    String productTypeStr = il.getProduct().getProductType();
                    HashMap yearsOfLines;
                    if (productTypeStr.equals(Consts.ProductType.BAR_A.getText())) {
                        yearsOfLines = (HashMap) result.get(new Long(0));
                    } else if (productTypeStr.equals(Consts.ProductType.BAR_B.getText())) {
                        yearsOfLines = (HashMap) result.get(new Long(1));
                    } else if (productTypeStr.equals(Consts.ProductType.BAR_C.getText())) {
                        yearsOfLines = (HashMap) result.get(new Long(2));
                    } else {
                        yearsOfLines = (HashMap) result.get(new Long(3));
                    }
                    ArrayList<Long> monthsOfQty = (ArrayList<Long>) yearsOfLines.get(new Long(year));
                    monthsOfQty.set(month, monthsOfQty.get(month) + Math.round(il.getSubTotal()));
                    monthsOfQty.set(0, monthsOfQty.get(0) + monthsOfQty.get(month));
                }
            }
        }
        return result;
    }

    // In the case of block & Cancel Sales Order --- Undo everything
    @Override
    public void cancelSalesOrder(String idStr) {
        try {
            SalesOrder salesOrder = getSalesOrderById(idStr);
            //TO DO
        } catch (NotExistException e) {
        }
    }
}
